package com.czr.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.czr.constant.GlobalConstant;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    /**
     * token私钥，不可以暴露
     */
    public static final String TOKEN_SECRET_KEY = "chizhourenkey";
    /**
     * token过期时间（小时）
     */
    public static int EXPIRE_TIME = 24;

    /**
     * 创建token
     *
     * @param userId   用户ID
     * @param userName 用户名
     * @return token
     */
    public static String createToken(String userId, String userName) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR, EXPIRE_TIME);
        return JWT.create()
                //签发对象
                .withAudience(userId + "")
                //载荷
                .withClaim("userName", userName)
                //签发时间
                .withIssuedAt(new Date())
                //有效时间
                .withExpiresAt(calendar.getTime())
                //加密
                .sign(Algorithm.HMAC256(TOKEN_SECRET_KEY));
    }

    /**
     * 验证token合法性
     *
     * @param token token
     * @return token是否合法
     */
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(TOKEN_SECRET_KEY)).build().verify(token);
    }

    /**
     * 通过token获取userId
     *
     * @return userId
     */
    public static Long getUserIdByToken(HttpServletRequest request) {
        String token = request.getHeader(GlobalConstant.HEADER_TOKEN);
        if(!StringUtils.isEmpty(token)){
            String userId = JWT.decode(token).getAudience().get(0);
            return Long.valueOf(userId);
        }else{
            return null;
        }

    }

    public static void main(String[] args) {
        JwtUtil.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIzIiwidXNlck5hbWUiOiJ4aWFvcWlhbmciLCJleHAiOjE2ODA3NzY4ODksImlhdCI6MTY4MDc3NjgyOX0.dJ8qFOVzjem4rVwmoK5GAaUyU7SKs4-RVu1slGA2_qo");
    }

}
